from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from typing import AsyncGenerator
from config.config import get_settings
import databases
from .model import Base

DATABASE_URL = get_settings().database_url
database = databases.Database(DATABASE_URL, min_size=2, max_size=5)
engine = create_async_engine(DATABASE_URL, echo=True)  # echo开启sql打印
async_session_maker = async_sessionmaker(engine, expire_on_commit=False)


class DALGetter:
    def __init__(self, dal_cls):
        self.dal_cls = dal_cls

    async def __call__(self):
        async with async_session_maker() as session:
            async with session.begin():
                yield self.dal_cls(session)


# 获取数据库连接
async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
    async with async_session_maker() as session:
        yield session


# 创建表
async def create_db_and_tables():
    from application.ucenter.model import User, UserRole, Role, RolePower, Power
    async with engine.begin() as conn:
        if get_settings().drop_all_table:
            await conn.run_sync(Base.metadata.drop_all)
        if get_settings().create_all_table:
            await conn.run_sync(Base.metadata.create_all)
